package com.heima.search.service.impl;

import com.heima.common.exception.CustException;
import com.heima.feigns.BehaviorFeign;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDTO;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Autowired
    BehaviorFeign behaviorFeign;
    @Autowired
    MongoTemplate mongoTemplate;

    @Async("taskExecutor") // 此方法  会调用 taskExecutor对应的线程池 异步执行
    @Override
    public void insert(UserSearchDTO userSearchDto) {
        // 1. 校验参数   搜索词
        String searchWords = userSearchDto.getSearchWords();
        if (StringUtils.isBlank(searchWords)) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"搜索词为空");
        }
        // 2. 根据登录用户id  或  设备id  远程调用行为Feign接口查询对应的行为实体数据
        ResponseResult<ApBehaviorEntry> behaviorResult = behaviorFeign.findByUserIdOrEquipmentId(userSearchDto.getEntryId(), userSearchDto.getEquipmentId());
        if (!behaviorResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程查询行为实体失败");
        }
        ApBehaviorEntry behaviorEntry = behaviorResult.getData();
        if (behaviorEntry==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"行为实体不存在");
        }
        // 3. 根据行为实体的id  对应搜索词作为条件，查询是否已经有该历史记录
        ApUserSearch one = mongoTemplate.findOne(Query.query(Criteria.where("entryId").is(behaviorEntry.getId()).and("keyword").is(searchWords)), ApUserSearch.class);
        // 3. 1   如果有 修改时间
        if (one!=null) {
            one.setCreatedTime(new Date());
        }else {
            // 3.2  如果没有就新增
            one = new ApUserSearch();
            one.setEntryId(behaviorEntry.getId());
            one.setKeyword(searchWords);
            one.setCreatedTime(new Date());
        }
        mongoTemplate.save(one);

    }

    @Override
    public ResponseResult findUserSearch(UserSearchDTO userSearchDto) {
        // 1. 校验参数    size = 10   minBehotTime = new Date();
        Date minBehotTime = userSearchDto.getMinBehotTime();
        if (minBehotTime == null) {
            minBehotTime = new Date();
        }
        int size = 10;
        // 2. 查询行为实体 (用户id 设备id)
        ApUser user = AppThreadLocalUtils.getUser();
        ResponseResult<ApBehaviorEntry> behaviorResult = behaviorFeign.findByUserIdOrEquipmentId(user == null ? null : user.getId(), userSearchDto.getEquipmentId());
        if (!behaviorResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程查询行为实体失败");
        }
        ApBehaviorEntry behaviorEntry = behaviorResult.getData();
        if (behaviorEntry==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"行为实体不存在");
        }
        // 3. 查询mongo   行为实体id   创建时间  <  最小时间   按照创建时间降序排序  limit size
        List<ApUserSearch> apUserSearches = mongoTemplate.find(Query.query(Criteria.where("entryId").is(behaviorEntry.getId())
                .and("createdTime")
                .lt(minBehotTime))
                .with(Sort.by(Sort.Direction.DESC, "createdTime")
                ).limit(size), ApUserSearch.class);
        // 4. 返回数据
        return ResponseResult.okResult(apUserSearches);
    }
}
